<template>
  <view>
    <view class="status_bar">
      <!-- 这里是状态栏 -->
    </view>
    <!-- 导航栏 -->
    <u-navbar :autoBack="false" :border="false" bgColor="#f1f2f6">
      <template #left>
        <u-icon name="arrow-left" size="16" @click="goBack"></u-icon>
      </template>
      <template #center>
        <view class="search">
          <u-search ref="searchRef" placeholder="搜索" v-model="keywords" shape="square" :focus="autoFocus" :showAction="false"
            bg-color="#dde0e5" @change="changeSearch"></u-search>
        </view>
      </template>
    </u-navbar>

    <view class="container">
      <u-gap height="88rpx"></u-gap>
      <!-- 内容区域 -->
      <u-tabs :list="tabs" lineColor="#000" @click="clickTab" :current="currentTabIndex"></u-tabs>
      <scroll-view scroll-y class="content" @scrolltolower="loadMore" >
        <view v-show="keywords == ''">
          <view v-show="showEmptyState" class="empty">
            <image src="@/static/chat/search.png" mode="aspectFill" class="empty-image" />
            <view class="empty-text">输入关键词开始搜索</view>
          </view>
          <view v-show="!showEmptyState">
            <view class="content-find" v-show="currentTabIndex < 2 && contactPerson?.length > 0">
              <view class="content-find-title">
                <view class="content-find-title-left">猜你想找</view>
                <u-icon name="trash" color="#8f9091" size="18" @click="del(1)"></u-icon>
              </view>
              <view class="content-avatar">
                <view v-for="(item, index) in contactPerson" :key="index" class="content-avatar-item" @click="jumpSingleChat(item)">
                  <u-avatar :src="item.avatar" size="20" shape="square" v-if="item.avatar"></u-avatar>
                  <view class="avatar" v-else>{{ item.username.slice(-1) }}</view>
                  <view class="content-avatar-item-name">{{ item.username }}</view>
                </view>
              </view>
            </view>
            <u-gap height="20rpx"></u-gap>
            <view class="content-find" v-show="(currentTabIndex == 0 || currentTabIndex == 2) && contactGroup.length > 0">
              <view class="content-find-title">
                <view class="content-find-title-left">猜你想找</view>
                <u-icon name="trash" color="#8f9091" size="18" @click="del(2)"></u-icon>
              </view>
              <view class="content-avatar">
                <view v-for="(item, index) in contactGroup" :key="index" class="content-avatar-item" @click="jumpGroupChat(item)">
                  <image src="@/static/chat/group.png" mode="aspectFill" class="find-item-image" />
                  <view class="content-avatar-item-name">{{ item.group_name }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-show="keywords != ''">
          <view v-show="showEmptyStatus" class="empty">
            <image src="@/static/chat/empty.png" mode="aspectFill" class="empty-image" />
            <view class="empty-text">输入关键词开始搜索</view>
          </view>
          <view v-show="!showEmptyStatus">
            <view v-show="currentTabIndex == 0">
              <view class="search-content" v-if="personData?.length > 0">
                <view class="search-content-title">联系人</view>
                <view class="search-content-result">
                  <view v-for="(item, index) in personData.slice(0, 2)" :key="index" class="search-content-result-item" @click="jumpSingleChat(item)">
                    <u-avatar :src="item.avatar" size="40" shape="square" v-if="item.avatar"></u-avatar>
                    <view class="avatars" v-else>{{ item.username.slice(-2) }}</view>
                    <view style="margin-left: 20rpx;width: 440rpx;">
                      <view class="username">{{ item.username }}</view>
                      <view style="color: #999;font-size: 24rpx;">{{ item.pos_name }}</view>
                    </view>
                    <view class="operate-content">
                        <view class="operate-item" @click.stop="callPhone(item.phone)">
                          <image src="@/static/chat/phone.png" mode="aspectFill" class="icon-right"/>
                        </view>
                        <view class="operate-item" @click.stop="jumpDetail(item)">
                          <image src="@/static/chat/info.png" mode="aspectFill" class="icon-right"/>
                        </view>
                    </view>
                  </view>
                </view>
                <view class="search-bottom" @click="lookMore(1)">
                  <u-icon name="search" color="#739df6" size="20"></u-icon>
                  <view class="search-bottom-text">查看更多相关联系人</view>
                  <u-icon name="arrow-right" color="#999" size="20"></u-icon>
                </view>
              </view>
              <u-gap height="20rpx"></u-gap>
              <view class="search-content" v-if="groupData?.length > 0">
                <view class="search-content-title">群组</view>
                <view class="search-content-result">
                  <view v-for="(item, index) in groupData.slice(0, 2)" :key="index" class="search-content-result-item" @click="jumpGroupChat(item)">
                    <image src="@/static/chat/group.png" mode="aspectFill" style="width: 80rpx;height: 80rpx;" />
                    <view style="margin-left: 20rpx;width: 440rpx;">
                      <view class="username">{{ item.group_name }}</view>
                      <view class="tip">猜你想找</view>
                    </view>
                  </view>
                </view>
                <view class="search-bottom" @click="lookMore(2)">
                  <u-icon name="search" color="#739df6" size="20"></u-icon>
                  <view class="search-bottom-text">查看更多相关群组</view>
                  <u-icon name="arrow-right" color="#999" size="20"></u-icon>
                </view>
              </view>
            </view>
            <view v-show="currentTabIndex == 1">
              <view class="search-content">
                <view class="search-content-title">联系人</view>
                <view class="search-content-result">
                  <view v-for="(item, index) in personData" :key="index" class="search-content-result-item" @click="jumpSingleChat(item)">
                    <u-avatar :src="item.avatar" size="40" shape="square" v-if="item.avatar"></u-avatar>
                    <view class="avatars" v-else>{{ item.username.slice(-2) }}</view>
                    <view style="margin-left: 20rpx;width: 440rpx;">
                      <view class="username">{{ item.username }}</view>
                      <view style="color: #999;font-size: 24rpx;">{{ item.pos_name }}</view>
                    </view>
                    <view class="operate-content">
                      <view class="operate-item" @click.stop="callPhone(item.phone)">
                        <image src="@/static/chat/phone.png" mode="aspectFill" class="icon-right"/>
                      </view>
                      <view class="operate-item" @click.stop="jumpDetail(item)">
                        <image src="@/static/chat/info.png" mode="aspectFill" class="icon-right"/>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
              <u-loadmore :status="status" v-if="loading"/>
            </view>
            <view v-show="currentTabIndex == 2">
              <view class="search-content">
                <view class="search-content-title">群组</view>
                <view class="search-content-result">
                  <view v-for="(item, index) in groupData" :key="index" class="search-content-result-item" @click="jumpGroupChat(item)">
                    <image src="@/static/chat/group.png" mode="aspectFill" style="width: 80rpx;height: 80rpx;" />
                    <view style="margin-left: 20rpx;width: 440rpx;">
                      <view class="username">{{ item.group_name }}</view>
                      <view class="tip">猜你想找</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

  </view>
</template>

<script>
import { useSearchStore, useUserStore, useChatStore, useSocketStore, useGroupStore } from '@/pinia-store/user'
import { chatApi } from '@/apis/cloud/chat'
import { mapStores } from 'pinia'
import { processImageUrl,objectToFormData } from "@/utils/chat"

export default {
  data() {
    return {
      keywords: '',
      currentTabIndex: 0,
      tabs: [
        { name: '综合' },
        { name: '联系人' },
        { name: '群组' }
      ],
      contactPerson: [],
      contactGroup: [],
      personData: [],
      groupData: [],
      userList: [],
			pageSize: 20,
			pageNum: 1,
			total: 0,
      status: 'loadmore',
      userInfo: [],
      imInfo: [],
      loading: false,
      autoFocus: false,
    }
  },
  computed: {
    ...mapStores(useSearchStore, useUserStore, useChatStore, useSocketStore, useGroupStore),
    showEmptyState() {
      return (this.currentTabIndex == 0 && (this.contactPerson || []).length === 0 && (this.contactGroup || []).length === 0) || (this.currentTabIndex == 1 && (this.contactPerson || []).length === 0) ||
        (this.currentTabIndex === 2 && (this.contactGroup || []).length === 0)
    },
    showEmptyStatus() {
      if (this.currentTabIndex == 0) {
        return (this.personData || []).length === 0 && (this.groupData || []).length === 0
      }
      if (this.currentTabIndex == 1) {
        return (this.personData || []).length === 0
      }
      if (this.currentTabIndex == 2) {
        return (this.groupData || []).length === 0
      }
    }
  },
  onLoad() {
    this.contactPerson = this.searchStore.person || []
		this.contactGroup = this.searchStore.groups || []
    this.userInfo = this.userStore.user
    this.imInfo = this.chatStore.imInfo

  },
  onReady() {
    const systemInfo = uni.getSystemInfoSync()
    const isIOS = systemInfo.platform === 'ios' && systemInfo.environment === 'browser'
    if (!isIOS) {
      this.autoFocus = true
    }else{
      this.$nextTick(() => {
        this.$refs.searchRef?.focus?.()
        setTimeout(() => {
          const inputEl = this.$refs.searchRef?.$el?.querySelector('input')
          inputEl?.focus()
        }, 500)
      })
    }
  },
  methods: {
    clickTab(e) {
      this.pageNum = 1
      this.total = 0
      this.loading = false
      this.status = 'loadmore'
      this.personData = []
      this.groupData = []
      this.currentTabIndex = e.index
      if(e.index < 2 && this.keywords){
        this.getUser()
        this.getGroup()
      }
      if(e.index == 2 && this.keywords){
        this.getGroup()
      }
    },
    goBack() {
      uni.reLaunch({
        url: '/pages/chat/list/index'
      })
    },
    lookMore(e) {
      this.currentTabIndex = e
    },
    changeSearch() {
      this.pageNum = 1
      this.total = 0
      this.loading = false
      this.status = 'loadmore'
      this.personData = []
      this.groupData = []
      if(this.currentTabIndex == 0){
        this.getUser()
        this.getGroup()
      }else if(this.currentTabIndex == 1){
        this.getUser()
      }else{
        this.getGroup()
      }
    },
    loadMore() {
      if (this.status != 'nomore') {
        this.getUser();
      }
    },
    async getUser() {
      if (this.loading || this.status == 'nomore') return;
      this.loading = true
      this.status = 'loading'

      const params = {
				'data[keywords]': this.keywords,
				'data[pageSize]': this.pageSize,
				'data[page]': this.pageNum,
				url: 'index.php/users/Member/getList'
			}
			const msg = await chatApi(this.userInfo.token, params);
			if(msg.code === 200) {
        if(msg.data.data.length == 0){
          this.status = 'nomore'
          return;
        }
				if(this.pageNum === 1) {
					this.personData = msg.data.data
				}else {
          msg.data.data.forEach(item => {
            this.personData.push(item)
          })
				}
        this.pageNum++
				this.total = msg.data.total
			}else {
				this.status = ''
			}
      this.loading = false
    },
    async getGroup() {
      let params = {
        data :{
          keyword: this.keywords,
          account: this.imInfo.account,
          token: this.userInfo.token,
        },
        url: 'index.php/users/Group/search'
      }
      const msg = await chatApi(this.userInfo.token, objectToFormData(params))
      if(msg.code == 200){
        this.groupData = msg.data
      }else{
        console.log('查询失败')
      }
    },
    async jumpSingleChat(e) {
      const params = {
        data: {
          myAccount: this.userStore.user.chat_account,
          token: this.userStore.user.token,
          account: this.userStore.user.chat_account,
          friends: {
            friend_account: e.account,
            friend_username: e.username,
            friend_phone: e.phone,
          }
        },
        url: 'index.php/users/Index/updateMyFriends'
      }
      const msg = await chatApi(this.userStore.user.token, objectToFormData(params))

      if(msg.code === 200) {
        let person = this.searchStore.person || []
        if(person){
          const index = person.findIndex(historyItem => historyItem.id === e.id)
          if (index !== -1) {
            person.splice(index, 1)
          }
          person.unshift(e)
          if (person.length > 20) {
            person.pop()
          }
        }
        this.socketStore.nowDialogId = e.dialog_id
        uni.setStorageSync('nowDialogId', e.dialog_id)
        this.searchStore.setPerson(person)
        this.chatStore.setChat(msg.data)
        uni.setStorageSync('friend', JSON.stringify(msg.data))
        uni.redirectTo({
          url:'/pages/chat/message/chat/chat'
        })
      }
    },
    jumpGroupChat(e) {
      let groups = this.searchStore.groups || []
      if(groups){
        const index = groups.findIndex(historyItem => historyItem.group_id === e.group_id)
        if (index !== -1) {
          groups.splice(index, 1)
        }
        groups.unshift(e)
        if (groups.length > 20) {
          groups.pop()
        }
      }
      this.searchStore.setGroups(groups)
      this.socketStore.nowDialogId = e.dialog_id
      uni.setStorageSync('nowDialogId', e.dialog_id)
      this.groupStore.setGroup(e)
      uni.setStorageSync('groupMsg', JSON.stringify(e))
      uni.navigateTo({
        url: '/pages/chat/message/group'
      })
    },
    del(e) {
      if(e == 1){
        this.contactPerson = []
        this.searchStore.setPerson(null)
      }else{
        this.contactGroup = []
        this.searchStore.setGroups(null)
      }
    },
    jumpDetail(e) {
      let params = {
        id: e.cloud_worker_id,
        name: e.username,
        type: 'user',
        avatar: e.avatar
      }
      uni.navigateTo({
        url: '/pages/addressBook/details/grdetails',
        animationType: 'none',
        success: function(res) {
          res.eventChannel.emit('details', { item: params })
        }
      });
    },
    async callPhone(e) {
			const phoneNumber = e
			try {
				// #ifdef APP-PLUS
					await this.checkCallPermission();
				// #endif
				uni.makePhoneCall({
					phoneNumber: phoneNumber,
					success: () => {
						console.log('拨号成功')
					},
					fail: (err) => {
						console.error('拨号失败:', err);
						// 特殊处理国产手机
						this.handleManufacturerPermission(phoneNumber);
					}
				});
			} catch (error) {
				console.log(error)
				if (error === 'PERMISSION_DENIED_ALWAYS') {
					this.showPermissionGuide(); // 显示权限引导
				} else {
					uni.showToast({ title: '拨号权限被拒绝', icon: 'none' });
				}
			}
		},
		// 检查并申请电话权限
		async checkCallPermission() {
			return new Promise((resolve, reject) => {
				// #ifdef APP-PLUS
				if (plus.os.name === 'Android') {
				// 先检查当前是否已有权限
				plus.android.checkPermission('android.permission.CALL_PHONE',
					(e) => {
					if (e.success) {
						resolve(); // 已有权限
					} else {
						// 没有权限则申请
						plus.android.requestPermissions(
						['android.permission.CALL_PHONE'],
						(result) => {
							// 修改判断逻辑
							const granted = result.granted ||
										(result.denied.length === 0 &&
										result.deniedAlways.length === 0);
							granted ? resolve() : reject('PERMISSION_DENIED');
						},
						(err) => reject(err)
						);
					}
					},
					(err) => reject(err)
				);
				} else {
				resolve(); // iOS无需动态申请
				}
				// #endif

				// #ifndef APP-PLUS
				resolve(); // 非APP端无需处理
				// #endif
			});
		},
		// 处理国产手机特殊权限
		handleManufacturerPermission(phoneNumber) {
			// 小米、华为等可能需要额外权限
			if (plus.os.vendor === 'xiaomi' || plus.os.vendor === 'huawei') {
				uni.showModal({
					title: '权限提示',
					content: '请在系统设置中开启「电话」和「后台弹出界面」权限',
					confirmText: '去设置',
					success: (res) => {
						if (res.confirm) plus.runtime.openSettings();
					}
				});
			} else {
				// 尝试直接调用系统拨号界面
				plus.runtime.openURL(`tel:${phoneNumber}`);
			}
		},
		// 显示权限引导
		showPermissionGuide() {
			uni.showModal({
				title: '权限被永久拒绝',
				content: '需要电话权限才能拨号，请前往应用设置手动开启',
				confirmText: '去设置',
				success: (res) => {
				if (res.confirm) {
					// 跳转到应用详情页
					plus.runtime.openSettings();
				}
				}
			});
		}
  }
}
</script>

<style lang="scss" scoped>
.status_bar {
  height: var(--status-bar-height);
  width: 100%;
}

.search {
  width: calc(100vw - 120rpx);
  margin-left: 40rpx;
}

.container {
  background: #f1f2f6;
  height: 100vh;
  padding: 0 20rpx;
  overflow: hidden;
}

.content {
  height: calc(100% - 176rpx - var(--status-bar-height));
  padding: 10rpx 0;

  &-find {
    background: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    &-title {
      display: flex;
      justify-content: space-between;
      font-size: 28rpx;

      &-left {
        font-weight: bold;
      }
    }
  }

  &-avatar {
    display: flex;
    flex-wrap: wrap;
    font-size: 28rpx;

    &-item {
      background: #f8f8f8;
      border-radius: 8rpx;
      display: flex;
      align-items: center;
      padding: 10rpx 10rpx;
      margin-top: 20rpx;
      margin-right: 20rpx;

      &-name {
        margin-left: 10rpx;
        max-width: 400rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .find-item-image {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .search-content {
    background: #fff;
    border-radius: 16rpx;
    padding: 20rpx 20rpx 0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    &-title {
      font-size: 28rpx;
      color: #999;
    }

    &-result {
      &-item {
        display: flex;
        align-items: center;
        padding: 16rpx 0;
      }
    }

    .icon-right {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .search-bottom {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-top: 2rpx solid #f1f2f6;

    &-text {
      font-size: 28rpx;
      width: 584rpx;
      margin-left: 16rpx;
      color: #739df6;
    }
  }

  .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 20vh;

    &-image {
      width: 200rpx;
      height: 200rpx;
      opacity: 0.8;
      margin-bottom: 20rpx;
    }

    &-text {
      font-size: 28rpx;
      color: #999;
      margin-top: 10rpx;
    }
  }

  .username {
    font-size: 28rpx;
    margin-bottom: 10rpx;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis
  }

  .tip {
    background: #e1eeff;
    font-size: 24rpx;
    width: 120rpx;
    text-align: center;
    color: #3672c0;
    border-radius: 10rpx;
    padding: 6rpx 0;
  }

  .avatar {
    border-radius: 8rpx;
    width: 40rpx;
    height: 40rpx;
    background: #739df6;
    color: #fff;
    text-align: center;
    line-height: 40rpx;
    font-size: 24rpx;
  }

  .avatars {
    border-radius: 8rpx;
    width: 80rpx;
    height: 80rpx;
    background: #739df6;
    color: #fff;
    text-align: center;
    line-height: 80rpx;
    font-size: 28rpx;
  }

  .operate-content {
    display: flex;
    .operate-item {
      display: flex;
      width: 80rpx;
      height: 80rpx;
      align-items: center;
      justify-content: center;
    }
  }
}</style>
